import { DataSource } from "../db/sqlite.js";
import Path from 'path';
import { fileURLToPath } from 'url';

const __dirname = Path.dirname(fileURLToPath(import.meta.url));

class Service {
    async createTable(connection) {
        return connection.query('create table if not exists test(id int,name char,age int)');
    }

    async addRow(connection) {
        return connection.query('insert into test(id,name,age) values($id,$name,$age)', { id: Date.now(), name: 'aa', age: 10 });
    }

    async getList(connection, arg1, arg2) {
        console.log(arg1, arg2);
        // throw Error('test error');
        return connection.query('select * from test');
    }
}
(async () => {
    DataSource.verbose().register('test', {
        path: Path.resolve(__dirname, './dist/store.db'),
        trace(db, ...args) {
            console.log('===>', db.index, ...args);
        }
    });
    const service = DataSource.getService(Service, {
        dataSource: 'test',
        transaction: ['addRow', 'createTable', 'getList'],
        before: (name, ctx) => {
            console.log('-----before', name, ctx.args);
            return ctx.args;
        },
        after: (name, { error, data }) => {
            console.log('-----after', name, data, error);
            if (error) {
                return { aa: 'aa' };
            }
            return data;
        }
    });
    // await service.createTable();
    // await service.addRow();
    // for (let i = 0; i < 20; i++) {
    //     service.getList().then(a => console.log(a));
    console.log(await service.getList('aa', 'bb'));
    // }
})();